import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/BlankToolBarTool.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';

class ConfirmOrderPage extends StatefulWidget {
  double allPrice;
  int allNum;
  String order_id;
  ConfirmOrderPage({Key key, this.allNum, this.allPrice, this.order_id})
      : super(key: key);

  @override
  _ConfirmOrderPageState createState() => _ConfirmOrderPageState();
}

class _ConfirmOrderPageState extends State<ConfirmOrderPage> {
  String token = "";
  String totalPoint = "0";
  String use = "0";
  String remark = "", name = "";
  String pay = "0";
      BlankToolBarModel barModel = BlankToolBarModel();
  @override
  void initState() {
    super.initState();
                barModel.outSideCallback = focusNodeChange;

    getString(TOKEN).then((value) {
      token = value;
      buy();
    });
    totalPoint = APPLIC.userInfoMap['user_msg']['point'].toString();
    pay = widget.allPrice.toString();
    setState(() {});
  }
void focusNodeChange() {
    setState(() {});
  }

  @override
  void dispose() {
    barModel.removeFocusListeners();

    super.dispose();
  }
  buy() async {
    Map map = new Map();
    map['token'] = token;
    Response<String> response = await HttpUtil()
        .post(Api.BaseUrl + "/index.php/wap/Order/getSup", data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    if (code == 1) {
      name=userMap['data']['msg'];
      setState(() {
        
      });
    } else {
      userMap = null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text('确认交单',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: black)),
        backgroundColor: white,
        brightness: Brightness.light,
        iconTheme: IconThemeData(color: black_99),
        elevation: 0.5,
      ),
      body: BlankToolBarTool.blankToolBarWidget(
        context,
        model: barModel,
        body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(10), 0, 0),
            color: Colors.white,
            child: new GestureDetector(
              onTap: () {},
              child: new Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                      '订单总额',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black87),
                    ),
                  ),
                  Text(MONEY + widget.allPrice.toString(),
                      style: TextStyle(
                          color: mainColor,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                ],
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(1), 0, 0),
            color: Colors.white,
            child: new GestureDetector(
              onTap: () {},
              child: new Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                      '订单数',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black87),
                    ),
                  ),
                  Text(widget.allNum.toString(),
                      style: TextStyle(
                          color: mainColor,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                  Text("单",
                      style: TextStyle(
                          color: Colors.black87,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                ],
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(1), 0, 10),
            color: Colors.white,
            child: new GestureDetector(
              onTap: () {},
              child: new Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                      '交单给',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black87),
                    ),
                  ),
                  Text(name,
                      style: TextStyle(
                          color: Colors.black87,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                ],
              ),
            ),
          ),
          new Container(
            margin: EdgeInsets.fromLTRB(
                0.0, ScreenUtil.getInstance().setHeight(0), 0, 1),
            padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
            decoration: new BoxDecoration(
              color: Colors.white,
            ),
            child: TextField(
              maxLines: 4,
              minLines: 4,
              onChanged: (value) {
                remark = value;
              },
              cursorColor: mainColor,
              keyboardAppearance: Brightness.light,
              decoration: new InputDecoration(
                  hintText: "填写订单备注",
                  border: InputBorder.none,
                  hintStyle: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
            ),
          ),
          Container(
            padding: EdgeInsets.only(left: 10, right: 10),
            color: white,
            child: new Row(
              children: <Widget>[
                Text(
                  '使用积分',
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      color: Colors.black87),
                ),
                Container(width: 20),
                Expanded(
                  child: TextField(
                    cursorColor: mainColor,
                    onChanged: (value) {
                      use = value;
                      if (use == "") {
                        use = "";
                        pay = widget.allPrice.toString();
                      } else {
                        if (double.parse(use) >= widget.allPrice) {
                          use = widget.allPrice.floor().toString();
                          pay =
                              (widget.allPrice - double.parse(use)).toString();
                          setState(() {});
                        } else {
                          pay =
                              (widget.allPrice - double.parse(use)).toString();
                        }
                      }
                      pay = formatNum(double.parse(pay), 2);
                      setState(() {});
                    },
                    controller: TextEditingController.fromValue(
                        TextEditingValue(
                            text:
                                '${this.use == null ? "" : this.use}', //判断keyword是否为空
                            // 保持光标在最后

                            selection: TextSelection.fromPosition(TextPosition(
                                affinity: TextAffinity.downstream,
                                offset: '$use'.length)))),
                    keyboardAppearance: Brightness.light,
                    keyboardType: TextInputType.numberWithOptions(),
                    decoration: new InputDecoration(
                        hintText: "填写积分",
                        border: InputBorder.none,
                        hintStyle: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE))),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    use = totalPoint;
                    if (double.parse(use) >= widget.allPrice) {
                      use = widget.allPrice.floor().toString();
                      pay = (widget.allPrice - double.parse(use)).toString();
                    } else {
                      pay = (widget.allPrice - double.parse(use)).toString();
                    }
                    pay = formatNum(double.parse(pay), 2);
                    setState(() {});
                  },
                  child: Text(
                    '使用全部',
                    style: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                        color: Colors.blue),
                  ),
                )
              ],
            ),
          ),
          Container(
            height: 1,
            color: f0Color,
          ),
          Container(
            padding: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 10),
            color: white,
            child: new Row(
              children: <Widget>[
                Text(
                  '本次最多可使用',
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      color: Colors.black87),
                ),
                Text(
                  '$totalPoint',
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      color: mainColor),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
            margin: EdgeInsets.fromLTRB(
                0,
                ScreenUtil.getInstance()
                    .setHeight(ScreenUtil.getInstance().setHeight(DP_20)),
                0,
                0),
            color: Colors.white,
            child: new GestureDetector(
              onTap: () {},
              child: new Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                      '实际总额',
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                          color: Colors.black87),
                    ),
                  ),
                  Text(MONEY + pay.toString(),
                      style: TextStyle(
                          color: mainColor,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                ],
              ),
            ),
          ),
          new Container(
            width: double.infinity,
            margin: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_60)),
            height: ScreenUtil.getInstance().setHeight(DP_80),
            decoration: new BoxDecoration(
                color: mainColor, borderRadius: BorderRadius.circular(10.0)),
            child: new FlatButton(
              child: new Padding(
                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                child: new Text(
                  "确认交单",
                  style: new TextStyle(
                      color: Colors.white,
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                ),
              ),
              onPressed: () {
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (_) {
                      return new NetLoadingDialog(
                        loadingText: "提交中...",
                        bgColor: Color.fromARGB(255, 0, 0, 0),
                        requestCallBack: null,
                        outsideDismiss: false,
                      );
                    });
                register();
              },
            ),
          )
        ],
      ),
    ));
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }

  register() async {
    Map map = new Map();
    map['token'] = token;
    map['order_id'] = widget.order_id;
    map['point'] = use;
    map['remark'] = remark;
    map['sign_type'] = SignType.CONFIRM_JIAODAN_ORDER;
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.CONFIRM_JIAODAN_ORDER, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      Navigator.of(context).pop("1");
    }
    return true;
  }
}
